﻿using B.WMS.IWMSService.Warehousety;
using B.WMS.StandardReturn;
using B.WMS.WMSDtos.Warehousety;
using B.WMS.WMSEntities.Warehousety;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace B.WMS.WMSService.Warehousety
{
    public class LocationService : ApplicationService, ILocationService
    {
        private readonly IRepository<Location, Guid> _LocationRepository;

        public LocationService(IRepository<Location, Guid> locationRepository)
        {
            _LocationRepository = locationRepository;
        }

        public async Task<ApiResult<LocationDto>> AddLocation(CreateUpdateLocationDto input)
        {
            var location = ObjectMapper.Map<CreateUpdateLocationDto, Location>(input);
            location.LocationNo = AutoCode.AutoCode.GetCode("CK").Result.ResultData;
            await _LocationRepository.InsertAsync(location);
            return new ApiResult<LocationDto>() { Code = ApiCode.Success, ResultData = ObjectMapper.Map<Location, LocationDto>(location) };
        }

        public async Task<ApiResult< Location>> DeleteLocation(string id)
        {
            var location = await _LocationRepository.GetAsync(x=>x.LocationNo==id);
            await _LocationRepository.DeleteAsync(location);
            return new ApiResult<Location>() { Code = ApiCode.Success, ResultData = location };
        }

        public  async Task<ApiPaging<LocationDto>> GetLocaPage(PageInput input)
        {
            var query =await _LocationRepository.GetQueryableAsync();
            var totalData =  query.Count();
            var pageDatas = query.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
            var pageDtos = ObjectMapper.Map<List<Location>, List<LocationDto>>(pageDatas);
            var totalPage = (int)Math.Ceiling((double)totalData / input.PageSize);
            return new ApiPaging<LocationDto>
            {
                Code = ApiCode.Success,
                TotalData = totalData,
                TotalPage = totalPage,
                PageDatas = pageDtos
            };

        }

        public async Task<List<LocationDto>> GetLocation()
        {
            var location= _LocationRepository.GetListAsync();
            var res = ObjectMapper.Map<List<Location>,List<LocationDto>>(await location);
            return res;
        }

        public async Task<ApiResult<LocationDto>> UpdateLocation(CreateUpdateLocationDto input)
        {
            var location =await _LocationRepository.FirstOrDefaultAsync(x => x.LocationNo == input.LocationNo);
            if (location == null)
            {
                return  new ApiResult<LocationDto> { Code = ApiCode.UrlError, Message = "库位不存在" };
            }
            ObjectMapper.Map(input, location);
            await _LocationRepository.UpdateAsync(location);
            // 4. 返回结果
            return new ApiResult<LocationDto>
            {
                Code = ApiCode.Success,
                ResultData = ObjectMapper.Map<Location, LocationDto>(location)
            };
        }

        public async Task<FileResult> ExportWarehouseAsync()
        {
            // 1. 获取仓库数据（替换为你的实际查询）
            var list = await _LocationRepository.GetListAsync();
            var data = list.Select(x => new {
                locationNo=x.LocationNo,
                locationName=x.LocationName,
                lcapacity=x.Lcapacity,
                lprincipal=x.Lprincipal,
                lsort=x.Lsort,
                lstatus=x.Lstatus,
                remark=x.Remark,
            }).ToList();
            // 2. 生成Excel
            using var stream = new MemoryStream();
            await MiniExcel.SaveAsAsync(stream, data);
            stream.Position = 0;
            return new FileContentResult(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "warehouse.xlsx"
            };
        }
    }
}
